package com.isoftstone.common.service.impl;

import com.isoftstone.common.dao.SysUserRoleMapper;
import com.isoftstone.common.entity.SysRole;
import com.isoftstone.common.entity.SysUserRole;
import com.isoftstone.common.service.ISysUserRoleService;
import com.isoftstone.merchant.entity.role.PRoleUserKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SysUserRoleService implements ISysUserRoleService {
	
	@Autowired
	SysUserRoleMapper sysUserRoleMapper;

	@Transactional
	public void saveUserRole(String userId, String roleId) throws Exception {
		sysUserRoleMapper.deleteUserRole(userId);
		if(StringUtils.isNotBlank(roleId)){
			String[] sp = roleId.split(",");
			for (String s : sp) {
				sysUserRoleMapper.saveUserRole(userId, s);
			}
		}

	}

	@Override
	public List<SysRole> getRolesByUserId(String userId) throws Exception{
		return sysUserRoleMapper.getRolesByUserId(userId);
	}
	public void deleteUserRole(String userId) throws Exception{
		sysUserRoleMapper.deleteUserRole(userId);
	}

	@Override
	public List<String> getMenuIdsByUserId(String comUserCode) throws Exception {
		return sysUserRoleMapper.getMenuIdsByUserId(comUserCode);
	}

    @Override
    public List<PRoleUserKey> getroleIdByOperatorId(String operatorId) throws Exception {
        return sysUserRoleMapper.getroleIdByOperatorId(operatorId);
    }

    @Override
    public String getUserId(int roleId) throws Exception {
        return sysUserRoleMapper.getUserId(roleId);
    }

    @Override
    public void updateUserRoleByUserIdAndRoleId(String userId, String roleId) throws Exception {
		SysUserRole userRole=sysUserRoleMapper.getUserRoleByUserId(userId);//查询该用户已绑定角色
		if (userRole==null){//如果未绑定,插入操作
			sysUserRoleMapper.saveUserRole(userId,roleId);
		}else{//如果已绑定删除之前绑定，重新插入
			sysUserRoleMapper.deleteUserRole(userId);
			sysUserRoleMapper.saveUserRole(userId,roleId);
		}
    }


}
